package com.yifeng.servlet.admin;

import com.yifeng.common.Result;
import com.yifeng.factory.ServiceFactory;
import com.yifeng.service.NewsService;
import com.yifeng.servlet.BaseServlet;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

// 创建一个新的 NewsPublicServlet 类处理公开查询
@WebServlet("/news/*")
public class NewsPublicServlet extends BaseServlet {
    private final NewsService newsService = ServiceFactory.getNewsService();

    @Override
    protected void doHandle(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        if ("GET".equals(req.getMethod().toUpperCase())) {
            handleGet(req, resp, req.getPathInfo());
        } else {
            writeJson(resp, Result.fail(405,"请求方法错误"));
        }
    }

    private void handleGet(HttpServletRequest req, HttpServletResponse resp, String pathInfo) throws IOException {
        //如果路径包含ID，表示查询新闻详情
        if(pathInfo!=null && pathInfo.matches("/\\d+")){
            handleGetById(req,resp,pathInfo);
            return;
        }

        String statusParam=req.getParameter("status");

        try {
            Result result;
            if(statusParam==null || statusParam.trim().isEmpty()){
                //不指定状态，则查询所有新闻
                result=newsService.getAllNews(); //新的 返回所有新闻的方法
            } else {
                //指定状态，则按状态查询新闻
                int status=Integer.parseInt(statusParam);
                result=newsService.getNewsByStatus(status); //新的 按状态查询所有新闻的方法
            }
            writeJson(resp, result);
        } catch (NumberFormatException e){
            writeJson(resp, Result.fail(400,"参数格式错误"));
        } catch (Exception e){
            writeJson(resp, Result.fail(406,"查询新闻列表失败"));
        }
    }

    private void handleGetById(HttpServletRequest req,HttpServletResponse resp,String pathInfo) throws IOException {
        try {
            int newsId=Integer.parseInt(pathInfo.substring(1)); //去掉开头的"/"
            Result result=newsService.getNewsById(newsId);
            writeJson(resp,result);

        } catch(NumberFormatException e) {
            writeJson(resp, Result.fail(400,"参数格式错误"));
        } catch(Exception e){
            writeJson(resp, Result.fail(406,"获取新闻详情失败"));
        }
    }
}